package com.dolceplan.dolceapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class DolceAppService extends Service {
	private static final String TAG = "DolceAppService";
	public static final String BROADCAST_ACTION = "com.dolceplan.dolceapp";
	private final Handler handler = new Handler();
	Intent intent;
	Location newLocation;
			
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
			
	@Override
	public void onCreate() {
		super.onCreate();
    	intent = new Intent(BROADCAST_ACTION);
	}

	@Override
	public void onDestroy() {
		handler.removeCallbacks(updateOffers);
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		handler.removeCallbacks(updateOffers);
		
		// Acquire a reference to the system Location Manager
		LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

		// Define a listener that responds to location updates
		LocationListener locationListener = new LocationListener() {
		    public void onLocationChanged(Location location) {
		    	// Called when a new location is found by the network location provider.
		    	newLocation = location;
		    	Log.d(TAG, "Location Changed");
		    	//handler.post(updateOffers);
		    	UpdateOffersAsyncTask task = new UpdateOffersAsyncTask();
		    	task.execute(newLocation);
		    }
		    
		    public void onProviderEnabled(String provider) {
		    	// TODO Auto-generated method stub
		    }
		    
		    public void onProviderDisabled(String provider) {
		    	// TODO Auto-generated method stub
		    }
		    
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub					
			}
			
		};

		// Register the listener with the Location Manager to receive location updates
		// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 500, locationListener);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
	}

	private class UpdateOffersAsyncTask extends AsyncTask<Location, Void, String> {

		@Override
		protected String doInBackground(Location... params) {
			String dolceUrl = "http://www.osvid.org/DolceServer/getOffer_2.php";
    		Log.d(TAG, "Start runnable");
    		Log.d(TAG, newLocation.toString());
    		/* Get lat and lon to query database
    		//String lat = Double.toString(location.getLatitude());
        	//String lon = Double.toString(location.getLongitude());
    		//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            //nameValuePairs.add(new BasicNameValuePair("lat", lat));
            //nameValuePairs.add(new BasicNameValuePair("lon", lon))
    		*/
    		
        	String resultSQL = "";
           	InputStream is = null;		
                    
            // Http post
            try {
            	HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(dolceUrl);
                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.d(TAG, is.toString());
            } catch (Exception e) {
            	Log.e("log_tag", "Error in http connection "+e.toString());
            }
            
         // Convert response to string
            try {
            	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                	sb.append(line + "\n");
                }
                is.close();
                resultSQL=sb.toString();
                Log.i("info", resultSQL);
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result "+e.toString());
            }
    		        
    			
			return resultSQL;
		}
		
		@Override
	    protected void onPostExecute(String result) {
			// Parse and store in DolceApp
            try {
            	ArrayList<Offer> offerList;
            	Gson gson = new Gson();        	      	           	
            	Type listType = new TypeToken<ArrayList<Offer>>() {}.getType();
            	offerList = gson.fromJson(result, listType );        	
            	Log.i("gson", "# de ofertas:" + String.valueOf(offerList.size()));        	
            	DolceApp dolceApp = (DolceApp) getApplication();
            	dolceApp.setOfferList(offerList);      
            	dolceApp.setLocation(newLocation);
            	sendBroadcast(intent);
            } finally {
            	
            }	

	    }

		
		
		 
	    
	 }
	
	
	private Thread updateOffers = new Thread() {
    	public void run() {
    		String dolceUrl = "http://www.osvid.org/DolceServer/getOffer_2.php";
    		Log.d(TAG, "Start runnable");
    		Log.d(TAG, newLocation.toString());
    		/* Get lat and lon to query database
    		//String lat = Double.toString(location.getLatitude());
        	//String lon = Double.toString(location.getLongitude());
    		//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            //nameValuePairs.add(new BasicNameValuePair("lat", lat));
            //nameValuePairs.add(new BasicNameValuePair("lon", lon))
    		*/
    		
        	String resultSQL = "";
           	InputStream is = null;		
                    
            // Http post
            try {
            	HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(dolceUrl);
                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.d(TAG, is.toString());
            } catch (Exception e) {
            	Log.e("log_tag", "Error in http connection "+e.toString());
            }   	
        	        
            // Convert response to string
            try {
            	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                	sb.append(line + "\n");
                }
                is.close();
                resultSQL=sb.toString();
                Log.i("info", resultSQL);
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result "+e.toString());
            }
    		        
    		// Parse and store in DolceApp
            try {
            	ArrayList<Offer> offerList;
            	Gson gson = new Gson();        	      	           	
            	Type listType = new TypeToken<ArrayList<Offer>>() {}.getType();
            	offerList = gson.fromJson(resultSQL, listType );        	
            	Log.i("gson", "# de ofertas:" + String.valueOf(offerList.size()));        	
            	DolceApp dolceApp = (DolceApp) getApplication();
            	dolceApp.setOfferList(offerList);      
            	dolceApp.setLocation(newLocation);
            	sendBroadcast(intent);
            } finally {
            	
            }		

    		
    		
    	}
    }; 
}
